package com.ruoyi.dora.portal.service.impl;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.dora.portal.entity.SysMenu;
import com.ruoyi.dora.portal.entity.SysUser;
import com.ruoyi.dora.portal.mapper.SysMenuMapper;
import com.ruoyi.dora.portal.service.ISysMenuService;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author Rubble
 * @since 2021-07-20
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {


  @Resource
  private SysMenuMapper menuMapper;

  @Override
  public List<SysMenu> selectMenusByUser (SysUser user) {

    List<SysMenu> menus = new LinkedList<SysMenu>();
    // 管理员显示所有菜单信息
    if (user.getUserId() != null && 1L == user.getUserId()) {
      menus = menuMapper.selectMenuNormalAll();
    } else {
      menus = menuMapper.selectMenusByUserId(user.getUserId());
    }
    return getChildPerms(menus, 0);
  }

  /**
   * 根据父节点的ID获取所有子节点
   *
   * @param list     分类表
   * @param parentId 传入的父节点ID
   * @return String
   */
  private List<SysMenu> getChildPerms (List<SysMenu> list, int parentId) {
    List<SysMenu> returnList = new ArrayList<>();
    for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
      SysMenu t = iterator.next();
      // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
      if (t.getParentId() == parentId) {
        recursionFn(list, t);
        returnList.add(t);
      }
    }
    return returnList;
  }

  /**
   * 递归列表
   *
   * @param list
   * @param t
   */
  private void recursionFn (List<SysMenu> list, SysMenu t) {
    // 得到子节点列表
    List<SysMenu> childList = getChildList(list, t);
    t.setChildren(childList);
    for (SysMenu tChild : childList) {
      if (hasChild(list, tChild)) {
        recursionFn(list, tChild);
      }
    }
  }

  /**
   * 得到子节点列表
   */
  private List<SysMenu> getChildList (List<SysMenu> list, SysMenu t) {
    List<SysMenu> tlist = new ArrayList<>();
    Iterator<SysMenu> it = list.iterator();
    while (it.hasNext()) {
      SysMenu n = it.next();
      if (n.getParentId().longValue() == t.getMenuId().longValue()) {
        tlist.add(n);
      }
    }
    return tlist;
  }

  /**
   * 判断是否有子节点
   */
  private boolean hasChild (List<SysMenu> list, SysMenu t) {
    return getChildList(list, t).size() > 0 ? true : false;
  }

}
